CS50 Introduction to Artificial Intelligence with Python Lecture 6
第六讲的主题是Neural Networks,这里总结第六讲以及第六次作业。
课程地址:https://cs50.harvard.edu/ai/
备注:图片均来自课程课件。
由于这一讲主要是神经网络的内容,课程内容的回顾在此从略,主要回顾project。
Project
Traffic
def load_data(data_dir):
"""
Load image data from directory `data_dir`.
Assume `data_dir` has one directory named after each category, numbered
0 through NUM_CATEGORIES - 1. Inside each category directory will be some
number of image files.
Return tuple `(images, labels)`. `images` should be a list of all
of the images in the data directory, where each image is formatted as a
numpy ndarray with dimensions IMG_WIDTH x IMG_HEIGHT x 3. `labels` should
be a list of integer labels, representing the categories for each of the
corresponding `images`.
"""
files = os.listdir(data_dir)
images = []
labels = []
for file in files:
path = os.path.join(data_dir, file)
image_names = os.listdir(path)
label = int(file)
for image_name in image_names:
image = cv2.imread(os.path.join(path, image_name)) / 255.0
image = cv2.resize(image, (IMG_WIDTH, IMG_HEIGHT))
images.append(image)
labels.append(label)
return images, labels
def get_model():
"""
Returns a compiled convolutional neural network model. Assume that the
`input_shape` of the first layer is `(IMG_WIDTH, IMG_HEIGHT, 3)`.
The output layer should have `NUM_CATEGORIES` units, one for each category.
"""
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(
32, (3, 3), activation='relu', input_shape=(IMG_WIDTH, IMG_HEIGHT, 3)
),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation="relu"),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(NUM_CATEGORIES, activation="softmax")
])
model.compile(
optimizer="adam",
loss="categorical_crossentropy",
metrics=["accuracy"]
)
return model
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Doraemonzzz!
评论
ValineLivere